package com.qyhl.module_practice.study.detail;

import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.GlobalNewsBean;
import com.qyhl.webtv.commonlib.entity.news.NewsBean;
import com.qyhl.webtv.commonlib.utils.ItemSkipUtils;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.PRACTICE_STUDY_NEW)
public class PracticeNewStudyActivity extends BaseActivity implements PracticeNewStudyContract.PracticeNewStudyView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private PracticeNewStudyPresenter mPresenter;

    private List<NewsBean> mDataList = new ArrayList<>();

    private CommonAdapter<NewsBean> commonAdapter;

    private List<GlobalNewsBean> indexList;

    private String lastId = "0";

    private String sectionId;

    private String id;

    @Override
    protected int getContentView() {
        return R.layout.practice_activity_study_new;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new PracticeNewStudyPresenter(this);

        String titleName = getIntent().getStringExtra("title");
        id = getIntent().getStringExtra("id");

        title.setText(titleName);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new GridLayoutManager(this, 2));
        recycleView.setAdapter(commonAdapter = new CommonAdapter<NewsBean>(this, R.layout.practice_item_study_two, mDataList) {
            @Override
            protected void convert(ViewHolder holder, NewsBean newsBean, int position) {
                holder.setText(R.id.title, newsBean.getTitle());
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(PracticeNewStudyActivity.this)
                        .load(newsBean.getLogo())
                        .apply(new RequestOptions().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);
            }
        });

        mPresenter.getSectionId(id);
    }

    @Override
    protected void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (StringUtils.isNotEmpty(sectionId)) {
                    lastId = "0";
                    mPresenter.getData(sectionId, lastId);
                } else {
                    mPresenter.getSectionId(id);
                }
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getData(sectionId, lastId);
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                if (StringUtils.isNotEmpty(sectionId)) {
                    lastId = "0";
                    mPresenter.getData(sectionId, lastId);
                } else {
                    mPresenter.getSectionId(id);
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                setNews(mDataList);
                ItemSkipUtils.getInstance().itemSkip(indexList.get(position), PracticeNewStudyActivity.this, view);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @OnClick(R2.id.back_btn)
    public void onViewClicked() {
        finish();
    }

    @Override
    public void setIdResult(String sId) {
        sectionId = sId;
        if (StringUtils.isNotEmpty(sectionId)) {
            lastId = "0";
            mPresenter.getData(sectionId, lastId);
        } else {
            loadMask.setReloadButtonText("点击重试~");
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText("暂无任何内容！");
            }
        }
    }

    @Override
    public void setData(List<NewsBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        lastId = beanList.get(beanList.size() - 1).getID();
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    /**
     * 设置新闻
     */
    private void setNews(List<NewsBean> beanList) {
        indexList = new ArrayList<>();

        //数据类型转换
        for (int i = 0; i < beanList.size(); i++) {
            NewsBean bean = beanList.get(i);
            boolean hasPicture = StringUtils.isPictureSuccess(bean.getLogo());
            String type = "", pOne = "", pTwo = "", pThree = "";
            int style = 0;
            switch (bean.getType()) {
                case "1"://普通新闻
                    type = "1";
                    switch (bean.getPluralPicsFlag()) {
                        case 0:
                            style = bean.getCommonStyle();
                            break;
                        case 1://三图
                            style = 4;
                            break;
                        case 2:
                            style = 3;
                            break;
                        default:
                            style = bean.getCommonStyle();
                            break;
                    }
                    break;
                case "2"://图片新闻
                    type = "2";
                    break;
                case "3"://直播
                    type = "9";
                    break;
                case "4"://标题新闻
                    type = "8";
                    break;
                case "5"://视频新闻
                    type = "3";
                    style = bean.getVideoStyle();
                    break;
                case "8"://互动直播
                    bean.setID(bean.getRoomId());//将roomId设置成通用Id
                    type = "5";
                    break;
                case "101"://抓取新闻
                    type = "10";
                    break;
                default:
                    break;
            }
            indexList.add(new GlobalNewsBean(bean.getTitle(), bean.getID(), bean.getRedirectURL(), bean.getLogo(), style, bean.getPublishDate(), type, Integer.parseInt(bean.getHitCount()), bean.getSource(), bean.getCatalogID(), hasPicture, pOne, pTwo, pThree, bean.getLivetype(), bean.getCommentCount()));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_STUDY);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_STUDY);
    }
}
